package com.media.revision;

import static android.animation.ObjectAnimator.ofPropertyValuesHolder;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.baselibrary.MessageBus;
import com.baselibrary.base.TabPagerAdapter;
import com.baselibrary.utils.DoubleUtils;
import com.baselibrary.utils.EventBusUtils;
import com.baselibrary.utils.MediaFileUtils;
import com.baselibrary.utils.ScreenUtils;
import com.baselibrary.utils.StatusBarUtil;
import com.baselibrary.utils.ToastUtils;
import com.media.AlbumManageUtils;
import com.media.MediaGlideLoader;
import com.media.PhotoViewPager;
import com.media.R;
import com.media.fragment.AllMediaFragment;
import com.media.fragment.PictureFragment;
import com.media.fragment.VideoFragment;
import com.media.image.ImageModel;
import com.media.image.ImageUtils;
import com.media.image.ImageWork;
import com.media.image.ViewPagerCacheBean;
import com.media.revision.adapter.ImagrListAdapter;
import com.media.revision.adapter.PreviewPageAdapter;
import com.media.revision.adapter.RevisionAdapter;
import com.media.revision.adapter.SelectListAdapter;
import com.media.utils.FileSizeUtil;
import com.media.utils.MediaCommonUtil;
import com.media.utils.TabLayout;
import com.xinlan.imageeditlibrary.EditImageFragment;
import com.xinlan.imageeditlibrary.EditImgMainActivity;
import com.xinlan.imageeditlibrary.editimage.model.SpacesItemDecoration;
import com.xinlan.imageeditlibrary.editimage.utils.DensityUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Objects;
import java.util.Set;

import com.media.publish.ReleaseDynamicActivity;

/**
 * 新发布界面 相册选择
 */
public class RevisionMediaActivity extends AppCompatActivity implements View.OnClickListener, RevisionAdapter.OnPreviewClickListener, RevisionAdapter.OnSelectClickListener {

    private static final int RESULT_CAMERA = 100;

    private TextView confirm, mTvShowType, mTvSelectCount;
    private LinearLayout back, mLlTitle, mLlSelect;
    private GridView mGridView;
    private ListView mediaListView;
    private View imageContainer, previewContainer;
    private ImagrListAdapter typeAdapter;
    private ImageWork mImageWork;//图片加载类
    public ArrayList<ImageModel> imageList = new ArrayList<>();//所有相册图片
    public ArrayList<ImageModel> videoList = new ArrayList<>();//所有视频
    public ArrayList<ImageModel> mediaList = new ArrayList<>();//所有相册和视频，，在选择相册文件夹或者视频文件夹的时候会被清空
    public ArrayList<ImageModel> typeImageList = new ArrayList<>();//所有相册图片文件夹
    public ArrayList<ImageModel> selectImageList = new ArrayList<>();//选中图片

    public ArrayList<ImageModel> flImageList = new ArrayList<>();//单独文件夹的图片
    public ArrayList<ImageModel> flVideoList = new ArrayList<>();//单独文件夹的视频

    public int max = 9;
    public int number = 9;
    private int count = 0;
    private String type = ImageModel.TYPE_ALL, fileType = ImageModel.TYPE_ALL;

    private RecyclerView mRvSelect;
    private SelectListAdapter mSelectListAdapter;
    private final String mSchemeVideo = "scheme://release/releaseVideoRecord";
    private final String mVideoEditScheme = "scheme://main/mainVideoEditActivity";
    private final String mVideoTrimScheme = "scheme://video/TrimActivity";
    private final String mCreateAgency = "scheme://main/CreateAgencySecondActivity";
    private int mJumpType;//从发布界面 选择拍照 或者 相册 过来的
    private boolean mIsVisibility, isForResult, isShowEdit;
    public static final int mMaxDuration = 1000 * 300;//选怎视频的最大时长
    public static final int mMinDuration = 1000 * 3;//选怎视频的最小时长
    //因为ViewPager的预加载 以下Map储存每个View的状态，当前正在显示的View里重新复制数据.
    public LinkedHashMap<Integer, ViewPagerCacheBean> mViewPagerCacheMap = new LinkedHashMap<>();
    public LinkedHashMap<String, VideoView> mFirstVideoViewMap = new LinkedHashMap<>();//首次点开视频才会使用
    public LinkedHashMap<String, ImageView> mFirstIvControlViewMap = new LinkedHashMap<>();//首次点开视频才会使用
    private VideoView mLastVideoView;
    private ImageView mLastVideoControl;
    private PhotoViewPager imagePager;
    private PreviewPageAdapter mPreviewPageAdapter;
    private TabLayout mTabLayout;


    private TextView mTvFolderEmpty;
    private ViewPager mVpGallery;
    private TabLayout mTabGalleryType;

    private VideoFragment mVideoFragment;
    private PictureFragment mPictureFragment;
    private AllMediaFragment mAllMediaFragment;

    private View imageSelec, videoSelec, mAllSelec;
    private Handler handler;
    //是否通过eventbus 传值
    private boolean isPassEventbus;

    public final ArrayList<String> mTabTitle = new ArrayList<>();
    ArrayList<Fragment> mListFragment = new ArrayList<>();
    BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(final Context context, final Intent intent) {
            String action = intent.getAction();

            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                //亮屏幕

            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                //息屏
            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                //解锁
            } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) {
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.revision_media_activity_media);
        MediaFileUtils.addActivity(this);
        StatusBarUtil.setTranslucentStatus(this);
        MediaCommonUtil.setStatusBarDarkTheme(this, false);
        getIntentData();
        initView();
        initData();

        switch (type) {
            case ImageModel.TYPE_ALL:
                flImageList.addAll(imageList);
                flVideoList.addAll(videoList);

                mAllMediaFragment.setList(mediaList);
                mPictureFragment.setList(flImageList);
                mVideoFragment.setList(flVideoList);
                new Thread(new Runnable() {//开启两个线程分别获取图片和视频
                    @Override
                    public void run() {
                        imageList = ImageUtils.getImages(RevisionMediaActivity.this, handler);
                        videoList = ImageUtils.getVideos(RevisionMediaActivity.this, handler);
                    }
                }).start();
                break;
            case ImageModel.TYPE_IMAGE:
                flImageList.addAll(imageList);
                mAllMediaFragment.setList(mediaList);
                mPictureFragment.setList(flImageList);
                new Thread(new Runnable() {//开启子线程获取图片
                    @Override
                    public void run() {
                        imageList = ImageUtils.getImages(RevisionMediaActivity.this, handler);
                    }
                }).start();
                break;
            case ImageModel.TYPE_VIDEO:
                flVideoList.addAll(videoList);
                mAllMediaFragment.setList(mediaList);
                mVideoFragment.setList(flVideoList);
                new Thread(new Runnable() {//开启子线程获取视频
                    @Override
                    public void run() {
                        videoList = ImageUtils.getVideos(RevisionMediaActivity.this, handler);
                    }
                }).start();
                break;
        }

        if (number == 1 && type.equals(ImageModel.TYPE_IMAGE)) {
            imageList.add(0, new ImageModel("", "", "", ImageModel.TYPE_CAMERA));
        }

        getTypeImageDate();
        max = number;
        selectImageList = new ArrayList<>();
        mSelectListAdapter = new SelectListAdapter(getLayoutInflater(), RevisionMediaActivity.this, mImageWork);
        mRvSelect.setAdapter(mSelectListAdapter);
        listenerContainer();
        IntentFilter filter = new IntentFilter();
        registerReceiver(filter);

//        mSelectListAdapter = getIntent().getStringArrayListExtra("selectImageList");
//        notifyData();
    }

    @SuppressLint("HandlerLeak")
    private void initData() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        mPictureFragment.addData((ArrayList<ImageModel>) msg.obj);
                        mAllMediaFragment.addData((ArrayList<ImageModel>) msg.obj);
                        if (mPreviewPageAdapter != null) {
                            mPreviewPageAdapter.notifyDataSetChanged();
                        }
                        break;
                    case 2:
                        mVideoFragment.addData((ArrayList<ImageModel>) msg.obj);
                        mAllMediaFragment.addData((ArrayList<ImageModel>) msg.obj);
                        if (mPreviewPageAdapter != null) {
                            mPreviewPageAdapter.notifyDataSetChanged();
                        }
                        break;
                }
            }
        };
        mImageWork = new ImageWork(this);
        mAllMediaFragment = new AllMediaFragment(this, mImageWork, ImageModel.TYPE_ALL);
        mPictureFragment = new PictureFragment(this, mImageWork, ImageModel.TYPE_IMAGE);
        mVideoFragment = new VideoFragment(this, mImageWork, ImageModel.TYPE_VIDEO);


        if (type.equals(ImageModel.TYPE_IMAGE)) {
            mTabTitle.add("照片");
            mListFragment.add(mPictureFragment);
            mTabGalleryType.addTab(mTabGalleryType.newTab().setText("照片"));
        } else if (type.equals(ImageModel.TYPE_VIDEO)) {
            mTabTitle.add("视频");
            mListFragment.add(mVideoFragment);
            mTabGalleryType.addTab(mTabGalleryType.newTab().setText("视频"));
        } else {

            mTabTitle.add("全部");
            mTabTitle.add("照片");
            mTabTitle.add("视频");
            mListFragment.add(mAllMediaFragment);
            mListFragment.add(mPictureFragment);
            mListFragment.add(mVideoFragment);
            mTabGalleryType.addTab(mTabGalleryType.newTab().setText("全部"));
            mTabGalleryType.addTab(mTabGalleryType.newTab().setText("照片"));
            mTabGalleryType.addTab(mTabGalleryType.newTab().setText("视频"));
        }
        mTabGalleryType.setIndictorWidth(30);


        TabPagerAdapter mTabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
        mTabPagerAdapter.setFragments(mListFragment);
        mTabPagerAdapter.setData(mTabTitle);
        mVpGallery.setAdapter(mTabPagerAdapter);
        mTabGalleryType.setupWithViewPager(mVpGallery);
        mVpGallery.setOffscreenPageLimit(mListFragment.size());

        mAllMediaFragment.setOnPreviewClickListener(this);
        mAllMediaFragment.setOnSelectClickListener(this);

        mVideoFragment.setOnPreviewClickListener(this);
        mVideoFragment.setOnSelectClickListener(this);

        mPictureFragment.setOnPreviewClickListener(this);
        mPictureFragment.setOnSelectClickListener(this);

    }


    private void getIntentData() {
        type = getIntent().getStringExtra("type");
        mIsVisibility = getIntent().getBooleanExtra("isVisibility", false);
        isForResult = getIntent().getBooleanExtra("isForResult", false);
        isShowEdit = getIntent().getBooleanExtra("isShowEdit", false);
        isPassEventbus = getIntent().getBooleanExtra("isPassEventbus", false);
        number = getIntent().getIntExtra("maxstr", 9);
        mJumpType = getIntent().getIntExtra("jumpType", 0);
    }

    private void registerReceiver(IntentFilter filter) {
        // 屏幕灭屏广播
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        // 屏幕亮屏广播
        filter.addAction(Intent.ACTION_SCREEN_ON);
        // 屏幕解锁广播
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mBatInfoReceiver, filter);
    }


    private void initView() {
        confirm = findViewById(R.id.tv_next);
        back = findViewById(R.id.ll_back);
        mTvShowType = findViewById(R.id.tv_showType);
        mLlTitle = findViewById(R.id.ll_title);
        mGridView = findViewById(R.id.gv_main);
        mRvSelect = findViewById(R.id.rv_select);
        mLlSelect = findViewById(R.id.ll_select);
        mediaListView = findViewById(R.id.mediaListView);
        mTvFolderEmpty = findViewById(R.id.tv_folder_empty);
        imageContainer = findViewById(R.id.imageContainer);
        mTvSelectCount = findViewById(R.id.tv_selectcount);
        previewContainer = findViewById(R.id.previewContainer);
        mTabGalleryType = findViewById(R.id.tab_galleryType);
        mVpGallery = (ViewPager) findViewById(R.id.vp_gallery);

        mTabLayout = findViewById(R.id.tab_release_record);
        mTabLayout.addTab(mTabLayout.newTab().setText("相册"));
        mTabLayout.addTab(mTabLayout.newTab().setText("拍照片"));
        if (type.equals(ImageModel.TYPE_ALL) || type.equals(ImageModel.TYPE_VIDEO)) {
            mTabLayout.addTab(mTabLayout.newTab().setText("拍视频"));
        }
        mTabLayout.setIndictorWidth(30);
        Objects.requireNonNull(mTabLayout.getTabAt(0)).select();
        mTabLayout.addOnTabSelectedListener(new TabLayout.BaseOnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 2://拍视频
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mSchemeVideo));
                        intent.putExtra("typeVideo", "2");
                        intent.putExtra("type", type);
                        intent.putExtra("maxstr", max);
                        intent.putExtra("isPassEventbus", isPassEventbus);
                        startActivity(intent);
                        finish();
                        break;
                    case 1://拍照片
                        Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(mSchemeVideo));
                        intent2.putExtra("typeVideo", "1");
                        intent2.putExtra("type", type);
                        intent2.putExtra("maxstr", max);
                        intent2.putExtra("isPassEventbus", isPassEventbus);
                        startActivity(intent2);
                        finish();
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        mRvSelect.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(RevisionMediaActivity.this, 7)));
        mLlTitle.setOnClickListener(this);
        imageContainer.setOnClickListener(this);
        back.setOnClickListener(this);
    }


    @SuppressLint("SetTextI18n")
    private void initImageTypeListView() {
        View headView = LayoutInflater.from(getApplication()).inflate(R.layout.revision_media_item_image_list_header, null);
        View mRlAll = headView.findViewById(R.id.rl_all);
        View video = headView.findViewById(R.id.video);
        ImageView allIcon = headView.findViewById(R.id.all_icon);
        TextView allNum = headView.findViewById(R.id.all_num);
        mAllSelec = headView.findViewById(R.id.all_selec);
        imageSelec = headView.findViewById(R.id.image_selec);
        videoSelec = headView.findViewById(R.id.video_selec);
        if (mediaList.size() > 0) {//全部
            MediaGlideLoader.LoderLoadImageType(getApplication(), mediaList.get(0).path, allIcon);
        }

        if (type.equals(ImageModel.TYPE_IMAGE)) {
            video.setVisibility(View.GONE);
        }

        allNum.setText(mediaList.size() + "张");
        initSelectView();
        mediaListView.getLayoutParams().height = MediaCommonUtil.getScreenHeight(getApplication()) * 3 / 4;
        mediaListView.addHeaderView(headView);
        if (typeImageList == null) {
            mediaListView.setVisibility(View.GONE);
            mTvFolderEmpty.setVisibility(View.VISIBLE);
            return;
        }

        Collections.sort(typeImageList, new ImageModel());
        typeAdapter = new ImagrListAdapter(typeImageList, fileType, getLayoutInflater(), RevisionMediaActivity.this);
        mediaListView.setAdapter(typeAdapter);
        //这里的listView 只获取了相册的文件夹，视频的统一到了 video 所有视频里面
        mediaListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                removeImageTypeView(imageContainer);
                max = number;
                fileType = typeImageList.get(position - 1).fileName;
                mTvShowType.setText(fileType);
                mediaList.clear();
                flImageList.clear();
                flVideoList.clear();

                for (ImageModel imageModel : imageList) {
                    if (imageModel.fileName.equals(fileType)) {
                        flImageList.add(imageModel);
                        mediaList.add(imageModel);
                    }
                }
                for (ImageModel imageModel : videoList) {
                    if (imageModel.fileName.equals(fileType)) {
                        flVideoList.add(imageModel);
                        mediaList.add(imageModel);
                    }
                }

                mAllMediaFragment.setList(mediaList);
                mPictureFragment.setList(flImageList);
                mVideoFragment.setList(flVideoList);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initSelectView();
                        typeAdapter.setFileType(fileType);
                        typeAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
        mRlAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeImageTypeView(imageContainer);
                type = ImageModel.TYPE_ALL;
                fileType = ImageModel.TYPE_ALL;
                mediaList = AlbumManageUtils.getAllImgAndVideo(imageList, videoList);

                mTvShowType.setText("全部");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initSelectView();
                        typeAdapter.setFileType(fileType);
                        typeAdapter.notifyDataSetChanged();
                        mAllMediaFragment.setList(mediaList);
                        flImageList = ImageUtils.getImages(getApplication());
                        flVideoList = ImageUtils.getVideos(getApplication());
                        mPictureFragment.setList(flImageList);
                        mVideoFragment.setList(flVideoList);
                    }
                });
            }
        });
    }

    private void initSelectView() {
        if (fileType.equals(ImageModel.TYPE_IMAGE)) {
            imageSelec.setVisibility(View.VISIBLE);
            videoSelec.setVisibility(View.GONE);
            mAllSelec.setVisibility(View.GONE);
        } else if (fileType.equals(ImageModel.TYPE_VIDEO)) {
            imageSelec.setVisibility(View.GONE);
            mAllSelec.setVisibility(View.GONE);
            videoSelec.setVisibility(View.VISIBLE);
        } else if (fileType.equals(ImageModel.TYPE_ALL)) {
            imageSelec.setVisibility(View.GONE);
            mAllSelec.setVisibility(View.VISIBLE);
            videoSelec.setVisibility(View.GONE);
        } else {
            imageSelec.setVisibility(View.GONE);
            videoSelec.setVisibility(View.GONE);
            mAllSelec.setVisibility(View.GONE);
        }
    }

    private void listenerContainer() {
        mGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
                    if (!ImageUtils.hasHoneycomb()) {
                        mImageWork.setPauseWork(true);
                    }
                } else {
                    mImageWork.setPauseWork(false);
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        /**
         * 底部选择列表删除
         */
        mSelectListAdapter.setOnDeleteSelectClickListener(new SelectListAdapter.OnDeleteSelectClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDeleteSelect(ImageModel imageModel, int pos) {
                int i = mediaList.indexOf(imageModel);
                imageModel.setIsChecked(false);
                imageModel.setSelsctRanking(0);
                if (i != -1) {
                    mediaList.set(i, imageModel);
                }
                selectImageList.set(pos, imageModel);//先将其状态改变，在原有图片和视频数据处理过后在remove
                mediaList = AlbumManageUtils.notifyAllList(selectImageList, mediaList);
                flImageList = AlbumManageUtils.notifyImgList(selectImageList, flImageList);
                flVideoList = AlbumManageUtils.notifyImgList(selectImageList, flVideoList);
                selectImageList.remove(pos);
                count = selectImageList.size();
                if (mPreviewPageAdapter != null && previewContainer.getVisibility() == View.VISIBLE) {
                    mPreviewPageAdapter.setSelectImageList(selectImageList);
                    mPreviewPageAdapter.setCount(count, max, number);
                    mPreviewPageAdapter.notifyDataSetChanged();
                }
                notifyData();

            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                confirm.setEnabled(false);
                if (DoubleUtils.isFastDoubleClick()) return;
                if (selectImageList.size() > 0) {
                    if (type.equals(ImageModel.TYPE_IMAGE)) {
                        if (isShowEdit) {
                            ArrayList<String> mImgPathList = new ArrayList<>();
                            for (ImageModel imageModel : selectImageList) {
                                mImgPathList.add(imageModel.getPath());
                            }
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mCreateAgency));
                            intent.putExtra("position", mImgPathList);
                            setResult(RESULT_OK, intent);
                            finish();
                            return;
                        }
                        ////首页大改版，发布选择[图片] 直接跳转发布页
                       /* Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(mScheme));
                        intent.putExtra("result", AlbumManageUtils.startEditorAct(getApplicationContext(), selectImageList));
                        intent.putExtra("Dynamictype", 1);
                        startActivity(intent);*/
                        Intent intent = new Intent();
                        intent.setClass(RevisionMediaActivity.this, EditImgMainActivity.class);
                        intent.putStringArrayListExtra(EditImgMainActivity.FILE_PATH_LIST, AlbumManageUtils.startEditorAct(getApplicationContext(), selectImageList));
                        intent.putExtra("isForResult", isForResult);
                        intent.putExtra("isPassEventbus", isPassEventbus);
                        startActivityForResult(intent, 101);
                    } else if (type.equals(ImageModel.TYPE_VIDEO)) {
                        Intent intentVideo = null;
                        //跳转视频界面
                        if (selectImageList.get(0).getDuration() > 300 * 1000) {
                            //进入剪辑界面
                            intentVideo = new Intent(Intent.ACTION_VIEW, Uri.parse(mVideoTrimScheme));
                            intentVideo.putExtra("isAlbum", true);
                        } else {
                            intentVideo = new Intent(Intent.ACTION_VIEW, Uri.parse(mVideoEditScheme));
                            intentVideo.putExtra("isEdit", true);
                        }
                        intentVideo.putExtra("isPassEventbus", isPassEventbus);
                        intentVideo.putExtra("videoPath", selectImageList.get(0).getPath());//剪辑界面需要
                        intentVideo.putExtra("MP4_PATH", selectImageList.get(0).getPath());//编辑界面需要
                        startActivity(intentVideo);
                    }
                }
                confirm.setEnabled(true);
            }
        });
    }

    @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
    private void notifyData() {
        if (selectImageList.size() <= 0) {
            type = ImageModel.TYPE_ALL;
        } else {
            type = selectImageList.get(0).getType();
        }

        max = AlbumManageUtils.getSelectMax(type, number);
        if (selectImageList.size() == 0) {
            mLlSelect.setVisibility(View.GONE);
            mTvSelectCount.setVisibility(View.GONE);
            setViewpagerMargin(0);
        } else {
            mLlSelect.setVisibility(View.VISIBLE);
            mTvSelectCount.setVisibility(View.VISIBLE);
            setViewpagerMargin(ScreenUtils.dip2px(this, 100));
        }
        selectImageList = AlbumManageUtils.setSelectSort(selectImageList);
        mSelectListAdapter.setSelecImageList(selectImageList);
        mSelectListAdapter.notifyDataSetChanged();
        mTvSelectCount.setText("已选择" + count + "/" + max);
        confirm.setSelected((count > 0));
        if (count > 0) {
            confirm.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            confirm.setTextColor(Color.parseColor("#000000"));
        }

        mAllMediaFragment.upAdapterSelectState();
        mPictureFragment.upAdapterSelectState();
        mVideoFragment.upAdapterSelectState();


    }

    private void setViewpagerMargin(int bottom) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mVpGallery.getLayoutParams();
        lp.setMargins(0, 0, 0, bottom);
        mVpGallery.requestLayout();
    }

    /**
     * 获取文件夹列表
     *
     * @return
     */
    public Object getTypeImageDate() {
        typeImageList = ImageUtils.getTypeImageslist(this);
        initImageTypeListView();
        return typeImageList;
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ll_title) {
            if (imageContainer.isShown()) {
                removeImageTypeView(imageContainer);
            } else {
                startImageTypeView(imageContainer);
            }
        } else if (id == R.id.imageContainer) {
            removeImageTypeView(imageContainer);
        } else if (id == R.id.ll_back) {
            onBackPressed();
//            finish();
        }
    }

    int current = 0;
    private String mViewPagerType = "";
    private int onPageSelectedPos;//浏览模式，当前展示界面索引

    /**
     * 单张图预览
     *
     * @param imageModel
     */
    private void initImageGallery(ImageModel imageModel) {
        imagePager = findViewById(R.id.viewpager);
        ProgressBar mPreview_pro = findViewById(R.id.preview_pro);
        mPreviewPageAdapter = new PreviewPageAdapter(RevisionMediaActivity.this, mPreview_pro);
        mPreviewPageAdapter.setData(mediaList);
        mPreviewPageAdapter.setViewPagerCacheMap(mViewPagerCacheMap);
        mPreviewPageAdapter.setFirstVideoViewMap(mFirstVideoViewMap);
        mPreviewPageAdapter.setOnIndexOf(String.valueOf(mediaList.indexOf(imageModel)));
        imagePager.setAdapter(mPreviewPageAdapter);
        mPreviewPageAdapter.setCount(count, max, number);
        mPreviewPageAdapter.setSelectType(type);
        mViewPagerType = type;
        imagePager.setCurrentItem(mediaList.indexOf(imageModel));
        mPreviewPageAdapter.setSelectImageList(selectImageList);
        imagePager.setOffscreenPageLimit(0);
        mPreviewPageAdapter.setOnSelectTypeClickListener(new PreviewPageAdapter.OnSelectTypeClickListener() {
            @Override
            public void onSelectTypeClick(String selectType) {
                mViewPagerType = selectType;
            }
        });
        imagePager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                onPageSelectedPos = i;
                upDataViewPager(i, mViewPagerType);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        mPreviewPageAdapter.setOnCloseClickListener(new PreviewPageAdapter.OnCloseClickListener() {
            @Override
            public void onCloseClick(ArrayList<ImageModel> previewSelectImageList, int position, String selectType) {
                if (mViewPagerCacheMap.size() > 0) {
//                    if (mViewPagerCacheMap.containsKey(mCurrentPage)) {
//                        if (mViewPagerCacheMap.get(mCurrentPage) != null) {
//                            Objects.requireNonNull(mViewPagerCacheMap.get(mCurrentPage)).getVideoView().pause();
//                        }
//                    }
                    //上面注释代码 我都通过 mCurrentPage 去关了，为什么还没关掉。。就for循环把，节约开发时间
                    Set<Integer> keySet = mViewPagerCacheMap.keySet();
                    for (Integer key : keySet) {
                        if (Objects.requireNonNull(mViewPagerCacheMap.get(key)).getVideoView() != null) {
                            Objects.requireNonNull(mViewPagerCacheMap.get(key)).getVideoView().pause();
                        }
                    }
                    mViewPagerCacheMap.clear();
                }
                if (mFirstVideoViewMap.size() > 0) {
                    mFirstVideoViewMap.clear();
                }
                removePreviewView();
                selectImageList = previewSelectImageList;
                mediaList = AlbumManageUtils.notifyAllList(selectImageList, mediaList);
                flImageList = AlbumManageUtils.notifyImgList(selectImageList, flImageList);
                flVideoList = AlbumManageUtils.notifyImgList(selectImageList, flVideoList);
                count = selectImageList.size();
                notifyData();
            }
        });
        mPreviewPageAdapter.setOnSelectClickListener(new PreviewPageAdapter.OnSelectClickListener() {
            @Override
            public void onSelectListener(ArrayList<ImageModel> selectImageList) {
                mediaList = AlbumManageUtils.notifyAllList(selectImageList, mediaList);
                flImageList = AlbumManageUtils.notifyImgList(selectImageList, flImageList);
                flVideoList = AlbumManageUtils.notifyImgList(selectImageList, flVideoList);
                count = selectImageList.size();
                notifyData();
            }
        });
    }


    private void removePreviewView() {
        // previewContainer.setVisibility(View.GONE);
        removeImageTypeView(previewContainer);
        //imageAdapter.notifyDataSetChanged();
        //删除多个元素
        Iterator<ImageModel> it = selectImageList.iterator();
        while (it.hasNext()) {
            ImageModel imageModel = it.next();
            if (!imageModel.isChecked) {
                it.remove();
            }
        }
        if (selectImageList.size() > 0) {
            if (current > selectImageList.size()) {
                current = 0;
            }
        }

    }

    private void startImageTypeView(View view) {
        float y = MediaCommonUtil.getScreenHeight(getApplication());
        //imageContainer.setVisibility(View.VISIBLE);
        view.setVisibility(View.VISIBLE);
        PropertyValuesHolder tlY = PropertyValuesHolder.ofFloat("translationY", y, 0.0f);
        PropertyValuesHolder tlX = PropertyValuesHolder.ofFloat("translationX", 0.0f, 0.0f);
//        ObjectAnimator anim = ofPropertyValuesHolder(imageContainer, tlX, tlY);
        ObjectAnimator anim = ofPropertyValuesHolder(view, tlX, tlY);
        anim.setDuration(300).start();
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
            }
        });

    }

    private void removeImageTypeView(final View view) {
        float y = MediaCommonUtil.getScreenHeight(getApplication());
        PropertyValuesHolder tlY = PropertyValuesHolder.ofFloat("translationY", 0.0f, y);
        PropertyValuesHolder tlX = PropertyValuesHolder.ofFloat("translationX", 0.0f, 0.0f);
//        ObjectAnimator anim = ofPropertyValuesHolder(imageContainer, tlX, tlY);
        ObjectAnimator anim = ofPropertyValuesHolder(view, tlX, tlY);
        anim.setDuration(300).start();
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
//                imageContainer.setVisibility(View.GONE);
                view.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBatInfoReceiver != null) {
            unregisterReceiver(mBatInfoReceiver);
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (previewContainer.isShown()) {
                if (mPreviewPageAdapter != null && mPreviewPageAdapter.mOnKeyDownClickListener != null)
                    mPreviewPageAdapter.mOnKeyDownClickListener.onKeyDownClick();
                return true;
            } else if (imageContainer.isShown()) {
                removeImageTypeView(imageContainer);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    public void upDataViewPager(int pos, String selectType) {
        if (mFirstVideoViewMap.size() > 0) {
            mLastVideoView = mFirstVideoViewMap.get("firstVideo");
            mLastVideoControl = mFirstIvControlViewMap.get("firstControlVideo");
            if (mLastVideoView != null) {
                mLastVideoView.pause();
            }
            if (mLastVideoControl != null) {
                mLastVideoControl.setSelected(false);
            }
            mFirstVideoViewMap.clear();
            mFirstIvControlViewMap.clear();
            mPreviewPageAdapter.setOnIndexOf(String.valueOf(pos));//这块的代码回头再改吧。。逻辑我自己都蒙蔽  垃圾代码。。。这里的setIndexOf 当从相册点击视频滑动到图片 再滑回视频，
            // 结果判断indexoOf，就会对 mFirstVideoViewMap 进行put ，然后就是导致 mLastVideoView 停止的视频出错
        }

        if (mLastVideoView != null) {
            mLastVideoView.pause();
        }

        if (mLastVideoControl != null)
            mLastVideoControl.setSelected(false);

        if (!mViewPagerCacheMap.containsKey(pos))
            return;
        ViewPagerCacheBean mPagerCacheBean = mViewPagerCacheMap.get(pos);
        if (mPagerCacheBean == null)
            return;
        ImageModel mImageModel = mPagerCacheBean.getImageModel();
        TextView mTvSelectType = mPagerCacheBean.getTvSelectType();
        LinearLayout mLlSelectType = mPagerCacheBean.getLlSelectType();
        LinearLayout mLlPreviewSelect = mPagerCacheBean.getLlPreView();
        ImageView mIvPreviewSelect = mPagerCacheBean.getIvPreviewSelect();
        TextView mTvPreviewSelect = mPagerCacheBean.getTvPreviewSelect();
        ImageView mIvVideoControl = mPagerCacheBean.getIvVideoPlayState();
        VideoView videoView = mPagerCacheBean.getVideoView();
        if (mImageModel == null || mTvSelectType == null || mLlSelectType == null || mLlPreviewSelect == null || mIvPreviewSelect == null || mTvPreviewSelect == null)
            return;

        if (videoView != null) {
            videoView.resume();
            videoView.start();
            mLastVideoView = videoView;
        }

        if (mIvVideoControl != null) {
            mIvVideoControl.setSelected(true);
            mLastVideoControl = mIvVideoControl;
        }
        mIvPreviewSelect.setVisibility(mImageModel.getIsChecked() ? View.GONE : View.VISIBLE);
        mTvPreviewSelect.setVisibility(mImageModel.getIsChecked() ? View.VISIBLE : View.GONE);
        mTvPreviewSelect.setText(String.valueOf(mImageModel.getSelsctRanking()));
        /*if (selectType.equals(ImageModel.TYPE_ALL)) {
            mTvSelectType.setText("");
            mLlSelectType.setVisibility(View.GONE);
            mLlPreviewSelect.setEnabled(true);
        } else if (selectType.equals(ImageModel.TYPE_IMAGE) && mImageModel.getType().equals(ImageModel.TYPE_VIDEO)) {
            mTvSelectType.setText("选择图片时不能选择视频");
            mLlSelectType.setVisibility(View.VISIBLE);
            mLlPreviewSelect.setEnabled(false);
        } else if (selectType.equals(ImageModel.TYPE_VIDEO) && mImageModel.getType().equals(ImageModel.TYPE_IMAGE)) {
            mTvSelectType.setText("选择视频时不能选择照片");
            mLlPreviewSelect.setEnabled(false);
            mLlSelectType.setVisibility(View.VISIBLE);
        }*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case EditImgMainActivity.RESULT_PICTURE:
                if (resultCode == EditImgMainActivity.RESULTCODE_PICTURE) {
                    if (mJumpType == 1) {
                        Intent i = new Intent();
                        ArrayList<String> mPathList = data.getStringArrayListExtra(EditImageFragment.EXTRA_OUTPUT);
                        ArrayList<String> mEditImgAfterList = data.getStringArrayListExtra("mEditImgAfterList");
                        i.putExtra("result", mPathList);
                        i.putExtra("mEditImgAfterList", mEditImgAfterList);
                        i.putExtra("isPassEventbus", isPassEventbus);
                        setResult(EditImgMainActivity.RESULT_EDITIMGOVVER, i);
                        finish();
                        return;
                    }
                    ArrayList<String> mPathList = data.getStringArrayListExtra(EditImageFragment.EXTRA_OUTPUT);
                    if (isPassEventbus) {
                        //通过eventbus传值
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_select_img_video_path_list, mPathList);
                        return;
                    }
                    Intent intent = new Intent(RevisionMediaActivity.this, ReleaseDynamicActivity.class);
                    intent.putExtra("result", mPathList);
                    if (type.equals(ImageModel.TYPE_IMAGE)) {
                        intent.putExtra("Dynamictype", 1);
                    } else if (type.equals(ImageModel.TYPE_VIDEO)) {
                        intent.putExtra("Dynamictype", 2);
                    }
                    startActivity(intent);
                    //finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onPreviewClick(int i, ImageModel imageModel) {
//        previewContainer.setVisibility(View.VISIBLE);
        startImageTypeView(previewContainer);
        try {
            initImageGallery(imageModel);
        } catch (Exception e) {
            e.getMessage();
            ToastUtils.showShort(getApplicationContext(), e.getMessage());
        }
    }

    /**
     * 选择媒体文件回调
     *
     * @param i
     * @param imageModel
     * @param mediaType
     */
    @Override
    public void onSelectClick(int i, ImageModel imageModel, String mediaType) {

        if (!type.equals(ImageModel.TYPE_ALL) && !type.equals(imageModel.getType())) {
            ToastUtils.showShort(getApplicationContext(), "照片和视频不能同时选择");
            return;
        }

        count = selectImageList.size();
        double ImgSize = FileSizeUtil.getFileOrFilesSize(mediaList.get(i).path, FileSizeUtil.SIZETYPE_MB);

        if (type.equals(ImageModel.TYPE_IMAGE) && ImgSize <= 0) {
            ToastUtils.showShort(getApplication(), "图片已损坏");
            return;
        }

        if (imageModel.getType().equals(ImageModel.TYPE_VIDEO)) {
            if (ImgSize <= 0) {
                ToastUtils.showShort(getApplication(), "视频已损坏");
                return;
            } else if (imageModel.duration < mMinDuration) {
                ToastUtils.showShort(getApplication(), "视频太短啦~最少要够3秒哦~");
                return;
            }
        }

        if (count >= max && !imageModel.getIsChecked()) {
            if (max == 0) {
                ToastUtils.showShort(getApplication(), (type.equals(ImageModel.TYPE_IMAGE) ? "照片" : "视频") + "数量已满");
            } else {
                ToastUtils.showShort(getApplicationContext(), type.equals(ImageModel.TYPE_VIDEO) ? "最多只能选择" + max + "个视频" : "最多只能选择" + max + "张照片");

            }
        } else if (count >= max && imageModel.getIsChecked()) {
            count = count - 1;
            imageModel.setIsChecked(false);
            selectImageList.remove(imageModel);
        } else if (count < max && !imageModel.getIsChecked()) {
            count = count + 1;
            imageModel.setIsChecked(true);
            selectImageList.add(imageModel);
        } else if (count < max && imageModel.getIsChecked()) {
            count = count - 1;
            imageModel.setIsChecked(false);
            selectImageList.remove(imageModel);
        }
        mediaList = AlbumManageUtils.notifyAllList(selectImageList, mediaList);
        flImageList = AlbumManageUtils.notifyImgList(selectImageList, flImageList);
        flVideoList = AlbumManageUtils.notifyImgList(selectImageList, flVideoList);
        notifyData();
    }
}

